<template>
  <div class="page_main">
    <div class="header">
      <div class="title">广告制作表</div>
      <div class="fill_date">填表日期：{{ cuForm.fill_date || formatDate }}</div>
    </div>
    <div class="content">
      <el-form ref="cuForm" v-loading="formLoading" size="mini" :model="cuForm" :rules="rules">
        <table class="mailTable">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              <span class="tip">*</span>类型
            </td>
            <td colspan="3" class="column">
              <el-form-item class="margin-lr-sm text-left" style="margin-bottom: 0;">
                <el-radio-group v-model="cuForm.type" @change="changeAdMakeType">
                  <el-radio :label="1">外单</el-radio>
                  <el-radio :label="2">内单</el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
          </tr>
          <template v-if="cuForm.type === 1">
            <tr>
              <td class="firstTd column tip_td">
                <span class="tip">*</span>公司
              </td>
              <td class="column">
                <el-form-item prop="dept_id">
                  <el-select v-model="cuForm.dept_id" placeholder="请选择公司" style="width: 100%" @change="changeCompany">
                    <el-option v-for="item in companyArr" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </td>
              <td class="firstTd column tip_td">
                <span class="tip">*</span>项目
              </td>
              <td class="column">
                <el-form-item>
                  <el-select v-model="cuForm.customer_id" placeholder="请选择客户" filterable style="width: 100%"
                             @change="customerChange"
                  >
                    <el-option v-for="customer in customer_arr" :key="customer.id" :label="customer.name"
                               :value="customer.id"
                    />
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="column tip_td">
                <span class="tip">*</span>合同
              </td>
              <td class="column">
                <el-form-item prop="contract_info">
                  <el-select v-model="cuForm.contract_info" filterable value-key="id" placeholder="请选择合同"
                             style="width: 100%" @change="changeContract"
                  >
                    <el-option v-for="item in contractArr" :key="item.id" :label="item.name" :value="item" />
                  </el-select>
                </el-form-item>
              </td>
              <td class="column tip_td">
                <span class="tip">*</span>市场（时间段）
              </td>
              <td class="column">
                <el-form-item prop="market_info">
                  <el-select v-model="cuForm.market_info" value-key="id" size="mini" style="width: 100%"
                             placeholder="请选择时间段" @change="changeMarket">
                    <el-option v-for="item in marketArr" :key="item.id" :label="item.name" :value="item"/>
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr v-if="cuForm.bill_market_id">
              <td class="firstTd column tip_td">
                时间段
              </td>
              <td class="column">
                <div class="text-left">
                  <el-date-picker v-model="cuForm.daterange_arr" type="daterange" size="mini" range-separator="至"
                                  start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy年MM月dd日"
                                  readonly
                  />
                </div>
              </td>
              <td class="column tip_td">
                分类
              </td>
              <td class="column">
                <div class="text-left">
                  <el-tag v-if="cuForm.dict_class_out_name" size="mini">{{ cuForm.dict_class_out_name || '' }}</el-tag>
                </div>
              </td>
            </tr>
          </template>
          <!-- 内单显示字段 -->
          <template v-else-if="cuForm.type === 2">
            <tr>
              <td class="firstTd column tip_td">
                公司
              </td>
              <td class="column">
                <el-form-item>
                  <el-select v-model="cuForm.dept_id" placeholder="请选择公司" style="width: 100%" @change="changeCompany">
                    <el-option v-for="item in companyArr" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </td>
              <td class="column tip_td">
                合同
              </td>
              <td class="column">
                <el-form-item>
                  <el-select v-model="cuForm.contract_info" filterable value-key="id" placeholder="请选择合同"
                             style="width: 100%" @change="changeContract"
                  >
                    <el-option v-for="item in contractArr" :key="item.id" :label="item.name" :value="item" />
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="firstTd column tip_td">
                项目
              </td>
              <td class="column">
                <el-form-item>
                  <el-input v-model="cuForm.contract_info && cuForm.contract_info.customer_name" disabled />
                </el-form-item>
              </td>
              <td class="column tip_td">
                <span class="tip">*</span>分类
              </td>
              <td class="column">
                <el-form-item>
                  <el-form-item class="margin-lr-sm text-left" prop="dict_class_in_id" style="margin-bottom: 0;">
                    <el-radio-group v-model="cuForm.dict_class_in_id">
                      <el-radio v-for="(item, index) in dictInTypeArr" :key="item.id" :label="item.id">{{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="firstTd column tip_td">
                <span class="tip">*</span>上传画面
              </td>
              <td colspan="3" class="column">
                <el-form-item class="own-form__pic">
                  <upload-image :file-list-prop="uploadPicVOList" @upload-success="handleUploadSuccess"
                                @upload-remove="handleUploadRemove" @upload-preview="handleUploadPreview"
                  />
                </el-form-item>
              </td>
            </tr>
          </template>

          <!-- 历史制作单，外单才会显示 -->
          <tr v-if="cuForm.type===1 && tableDataHistory.length">
            <td class="firstTd column tip_td">
              历史制作单
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataHistory" size="mini" style="width: 100%">
                  <el-table-column label="历史制作单" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      <el-tag size="mini">{{ row.daterange_start + '~' + row.daterange_start }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="生成状态" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-tag v-if="row.gen_status===1" size="mini">未生成</el-tag>
                      <el-tag v-if="row.gen_status===2" type="warning" size="mini">部分生成</el-tag>
                      <el-tag v-if="row.gen_status===3" type="success" size="mini">全部生成</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="提交时间" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      {{ row.created_at ? row.created_at.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="通过时间" min-width="100" align="center" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                      {{ row.flow_passed_at ? row.flow_passed_at.substring(0, 10) : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="mark_name" label="标记类型" min-width="100" align="center" />
                  <el-table-column prop="mark_memo" label="备注" min-width="100" align="center" />
                  <el-table-column fixed="right" label="操作" width="200" align="center">
                    <template slot-scope="{row,$index}">
                      <el-button v-if="!row.mark_id" type="danger" size="mini" @click="handelSignFail(row, $index)">
                        标记
                      </el-button>
                      <el-button v-else type="danger" size="mini" @click="handelSignClear(row, $index)">
                        清除
                      </el-button>
                      <el-button size="mini" @click="toDetail(row.id)">
                        查看
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </td>
          </tr>

          <!-- 点位详细 -->
          <tr>
            <td class="firstTd column tip_td">
              <span class="tip">*</span>点位详情、选择画面
            </td>
            <td colspan="3" class="column">
              <el-card v-if="cuForm.bill_market_id || cuForm.type === 2"
                       style="margin: 15px 0;padding: 0 20px 20px 20px;"
              >
                <div class="text-right margin-top">
                  <el-button v-if="cuForm.type === 2" type="primary" size="mini" icon="el-icon-circle-plus-outline"
                             @click="showPositionSelection"
                  >
                    自助选位
                  </el-button>
                  <el-button type="success" size="mini" icon="el-icon-circle-plus-outline" @click="showAddMedia">
                    新增点位
                  </el-button>
                </div>

                <template v-if="tableDataMedia.length">
                  <div v-for="(item, index) in tableDataMedia" :key="item.id">
                    <el-divider content-position="center">
                      <div class="text-bold">
                        <span>{{ item.name }}</span>
                      </div>
                    </el-divider>

                    <template v-if="item.id===9">
                      <div class="margin-bottom-sm text-right" style="margin-top: -5px;">
                        <el-button type="primary" size="mini" icon="el-icon-files"
                                   :disabled="multipleSelection.length?false:true" @click="showChooseFrameAll"
                        >批量选择画面
                        </el-button>
                      </div>
                      <el-table :id="'tableDataMedia_' + index" :ref="'tableDataMedia_' + index" :data="item.list"
                                class="dataTable" size="mini" style="width: 100%" max-height="700px"
                                header-row-class-name="text-bold table-herder" row-class-name="choosed-data"
                                header-cell-class-name="choosed-data" show-summary :summary-method="getSummariesMedia"
                                @selection-change="selectionChange"
                      >
                        <el-table-column prop="name" label="项目名称" min-width="100" align="center" />
                        <el-table-column prop="media_type_spec" label="尺寸" min-width="100" align="center" />
                        <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                        <el-table-column prop="count" label="数量" min-width="100" align="center" />
                        <el-table-column prop="choose_info" label="画面" min-width="100" align="center">
                          <template slot-scope="{row,$index}">
                            <template v-if="row.choose_info && row.choose_info.length">
                              <span v-for="(val,idx) in row.choose_info" :key="val.name"
                                    class="margin-left-sm text-bold"
                              >{{ val.name + '（' + val.count + '）' }}</span>
                              <el-button type="text" class="margin-left" @click="showChooseFrame(row, $index, index)">
                                选择画面
                              </el-button>
                            </template>
                          </template>
                        </el-table-column>
                        <el-table-column type="selection" min-width="100" align="center" />
                      </el-table>
                    </template>
                    <template v-else>
                      <el-table :id="'tableDataMedia_' + index" :ref="'tableDataMedia_' + index" :data="item.list"
                                class="dataTable" size="mini" style="width: 100%" max-height="700px"
                                header-row-class-name="text-bold table-herder" row-class-name="choosed-data"
                                header-cell-class-name="choosed-data" show-summary :summary-method="getSummariesMedia"
                      >
                        <el-table-column prop="media_type_spec" label="尺寸" min-width="100" align="center" />
                        <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                        <el-table-column prop="count" label="数量" min-width="100" align="center">
                          <template slot-scope="{row,$index}">
                            <span>{{ row.count }}</span>
                            <el-button type="text" class="margin-left" @click="showChooseFrame(row, $index, index)">选择画面
                            </el-button>
                          </template>
                        </el-table-column>
                        <el-table-column prop="choose_info" label="画面(幅)" min-width="100" align="center">
                          <template slot-scope="{row,$index}">
                            <template v-if="row.choose_info && row.choose_info.length">
                              <span v-for="(val,idx) in row.choose_info" :key="val.name"
                                    class="margin-left-sm text-bold"
                              >{{ val.name + '（' + val.count + '）' }}</span>
                            </template>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </div>
                </template>

              </el-card>
            </td>
          </tr>

          <!-- 供应商 -->
          <tr>
            <td class="firstTd column tip_td">
              <span class="tip">*</span>分配供应商、小样配送
            </td>
            <td colspan="3" class="column">
              <el-card v-if="(cuForm.bill_market_id && cuForm.pics) || tableDataMedia.length"
                       style="margin: 15px 0;padding: 0 20px 20px 20px;"
              >
                <el-divider content-position="center">
                  <div class="text-bold">
                    <span class="text-green">分配供应商</span>
                  </div>
                </el-divider>
                <div class="margin-bottom-sm text-right" style="margin-top: -15px;">
                  <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="showSupplier()">
                    分配供应商
                  </el-button>
                </div>
                <el-table :data="tableDataSupplier" class="dataTable" size="mini" border style="width: 100%">
                  <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column label="画面" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <template v-if="row.choose_info && row.choose_info.length">
                        <span v-for="(val,idx) in row.choose_info" :key="val.name"
                              class="margin-left-sm text-bold"
                        >{{ val.name + '（' + val.count + '）' }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <!-- <el-button type="text" size="mini" class="margin-left" @click="editSupplierRow(row, $index)">编辑
                      </el-button> -->
                      <el-button type="text" size="mini" class="margin-left" @click="delSupplierRow($index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 小样 -->
                <template v-if="cuForm.has_sample">
                  <el-divider content-position="center">
                    <div class="text-bold">
                      <span class="text-red">小样配送</span>
                    </div>
                  </el-divider>

                  <el-table :data="tableDataSampleDeliver" class="own-table" size="mini" border style="width: 100%">
                    <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                    <el-table-column label="配送方式" min-width="100" align="center">
                      <template slot-scope="{row,$index}">
                        <el-form-item prop="rulesComm" :rules="rulesComm('select', '配送方式', row.type)">
                          <el-select v-model="row.type" placeholder="请选择配送方式" style="width: 100%;">
                            <el-option v-for="item in deliverTypeSampleList" :key="item.id" :label="item.name"
                                       :value="item.id"
                            />
                          </el-select>
                        </el-form-item>
                        <el-form-item v-if="row.type==3" prop="rulesComm"
                                      :rules="rulesComm('select', '跑腿平台', row.run_id)" style="margin-top: 0 !important;"
                        >
                          <el-select v-model="row.run_id" placeholder="请选择跑腿平台" style="width: 100%;">
                            <el-option v-for="item in dictRunArr" :key="item.id" :label="item.name" :value="item.id" />
                          </el-select>
                        </el-form-item>
                        <el-form-item v-if="row.type==3" prop="rulesComm"
                                      :rules="rulesComm('price', '跑腿费', row.run_cost)"
                        >
                          <el-input v-model.trim="row.run_cost" clearable placeholder="请输入跑腿费" />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="address" label="地址" min-width="100" align="center">
                      <template slot-scope="{row,$index}">
                        <el-form-item :prop="row.type==4?'rulesCommNoRequired':'rulesComm'"
                                      :rules="row.type==4?rulesCommNoRequired('textarea', '地址', row.address):rulesComm('textarea', '地址', row.address)"
                        >
                          <el-input v-model.trim="row.address" clearable type="textarea" :rows="1"
                                    placeholder="请输入地址"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-card>
            </td>
          </tr>

          <!-- 配送方式 -->
          <tr v-if="tableDataSupplier.length">
            <td class="firstTd column tip_td">
              <span class="tip">*</span>配送方式
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataDeliver" class="own-table" size="mini" style="width: 100%">
                  <el-table-column prop="supplier_name" label="供应商" min-width="100" align="center" />
                  <el-table-column label="配送方式" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('select', '配送方式', row.type)">
                        <el-select v-model="row.type" placeholder="请选择配送方式" style="width: 100%;">
                          <el-option v-for="item in deliverTypeList" :key="item.id" :label="item.name"
                                     :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item v-if="row.type==3" prop="rulesComm" :rules="rulesComm('select', '跑腿平台', row.run_id)"
                                    style="margin-top: 0 !important;"
                      >
                        <el-select v-model="row.run_id" placeholder="请选择跑腿平台" style="width: 100%;">
                          <el-option v-for="item in dictRunArr" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                      </el-form-item>
                      <el-form-item v-if="row.type==3" prop="rulesComm"
                                    :rules="rulesComm('price', '跑腿费', row.run_cost)"
                      >
                        <el-input v-model.trim="row.run_cost" clearable placeholder="请输入跑腿费" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="hope_time" label="期望送达时间" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('text', '期望送达时间', row.hope_time)">
                        <el-date-picker v-model="row.hope_time" clearable type="datetime" placeholder="选择期望送达时间"
                                        value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="地址" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('textarea', '地址', row.address)">
                        <el-input v-model.trim="row.address" clearable type="textarea" :rows="1" placeholder="请输入地址" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="memo" label="备注" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item>
                        <el-input v-model.trim="row.memo" clearable type="textarea" :rows="1" placeholder="请输入备注" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </td>
          </tr>

          <tr>
            <td class="firstTd colum tip_td">
              备注
            </td>
            <td colspan="3" class="column" style="padding: 15px 10px">
              <el-input v-model.trim="cuForm.memo" type="textarea" :rows="4" />
            </td>
          </tr>
        </table>
        <div class="margin-bottom">
          <FlowBtnRow :is-new-data="params.is_create" :is-applyer="cuForm.flow_applyer_id == userId"
                      :flow-status="cuForm.flow_status" :is-confirm="false" form-name="" @save="save" @submit="submit"
          />
        </div>
      </el-form>
    </div>

    <!-- 综合市场选择画面(弹出框) -->
    <el-dialog title="选择画面" :visible.sync="dialogVisibleFrameAll" width="60%" center>
      <el-form ref="cuFormFrameAll" v-loading="dialogLoading" :model="cuFormFrameAll">
        <table class="mailTable" style="width: 100%;">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              已选择
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataFrameAll" size="mini" style="width: 100%">
                  <el-table-column prop="name" label="项目名称" min-width="100" align="center" />
                  <el-table-column prop="media_type_spec" label="尺寸" min-width="100" align="center" />
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column prop="count" label="数量" min-width="100" align="center" />
                </el-table>
              </el-card>
            </td>
          </tr>
          <tr>
            <td class="firstTd column tip_td">
              <span class="tip">*</span>选择画面
            </td>
            <td colspan="3" class="column">
              <el-form-item class="margin-lr-sm text-left" prop="name" style="margin-bottom: 0;">
                <el-radio-group v-model="cuFormFrameAll.name">
                  <el-radio v-for="(item,index) in cuForm.pics" :key="index" :label="item.uuid">{{ item.uuid }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td class="firstTd column tip_td">
              示例图
            </td>
            <td colspan="3" class="column">
              <div class="flex flex-wrap align-center margin-top-sm">
                <div v-for="(item,index) in cuForm.pics" :key="index"
                     class="flex flex-direction align-center justify-between margin-left"
                >
                  <el-image style="width: 100px;height: 160px;" :src="item.pic_url" fit="contain"
                            :preview-src-list="picList"
                  />
                  <div>{{ item.uuid }}</div>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFrameAll = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitFrameAll">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 选择画面(弹出框) -->
    <el-dialog title="选择画面" :visible.sync="dialogVisibleFrame" width="60%" center>
      <el-form ref="cuFormFrame" v-loading="dialogLoading" :model="cuFormFrame" size="mini" label-position="top">
        <table class="mailTable" style="width: 100%;">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              已选择
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataFrame" size="mini" style="width: 100%">
                  <el-table-column v-if="cuFormFrame.media_type_id==9" prop="name" label="项目名称" min-width="100"
                                   align="center"
                  />
                  <el-table-column prop="media_type_spec" label="尺寸" min-width="100" align="center" />
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column prop="count" label="数量" min-width="100" align="center" />
                </el-table>
              </el-card>
            </td>
          </tr>
          <tr>
            <td class="firstTd column tip_td">
              <span class="tip">*</span>选择画面
            </td>
            <td colspan="3" class="column">
              <div class="flex flex-wrap" style="margin: 15px 0;">
                <el-card v-for="(item,index) in cuForm.pics" :key="index" class="margin-right margin-bottom"
                         style="padding: 0 20px 20px 20px;"
                >
                  <div class="flex flex-direction align-center justify-between" style="margin-top: 20px;">
                    <el-image style="width: 100px;height: 160px;" :src="item.pic_url" fit="contain"
                              :preview-src-list="[item.pic_url]"
                    />
                    <div>{{ item.uuid }}</div>
                  </div>
                  <el-form-item style="margin-bottom: 10px" :label="cuFormFrame.media_pic_type" :prop="item.uuid"
                                :rules="rulesCount(cuFormFrame.max_count, cuFormFrame[item.uuid])"
                  >
                    <el-input v-model.trim="cuFormFrame[item.uuid]" clearable min="0" type="number" placeholder="请输入数量"
                              style="width: 160px;"
                    >
                      <template slot="append">幅</template>
                    </el-input>
                  </el-form-item>
                </el-card>
              </div>
            </td>
          </tr>
        </table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFrame = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitFrame">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配供应商(弹出框) -->
    <el-dialog title="选择画面" :visible.sync="dialogVisibleFrameSupplier" width="60%" center>
      <el-form ref="cuFormFrameSupplier" v-loading="dialogLoading" :model="cuFormFrameSupplier" size="mini">
        <table class="mailTable" style="width: 100%;">
          <tr class="firstTr">
            <td class="firstTd column tip_td">
              分配供应商
            </td>
            <td colspan="3" class="column">
              <el-card style="margin: 15px 0;padding: 0 20px 20px 20px;">
                <el-table :data="tableDataFrameSupplier" size="mini" style="width: 100%">
                  <el-table-column label="画面(幅)" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <template v-if="row.choose_info && row.choose_info.length">
                        <span v-for="(val,idx) in row.choose_info" :key="val.name"
                              class="margin-left-sm text-bold"
                        >{{ val.name + '（' + val.count + '）' }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center" />
                  <el-table-column label="供应商" min-width="100" align="center">
                    <template slot-scope="{row,$index}">
                      <el-form-item prop="rulesComm" :rules="rulesComm('select', '供应商', row.supplier_info)">
                        <el-select v-model="row.supplier_info" size="mini" value-key="id" placeholder="请选择供应商"
                                   style="width: 100%;margin-top: 18px;"
                        >
                          <el-option v-for="item in supplierObj[row.media_pic_type_id]" :key="item.id"
                                     :label="item.name" :value="item"
                          />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </td>
          </tr>
          <tr>
            <td class="firstTd column tip_td">
              示例图
            </td>
            <td colspan="3" class="column">
              <div class="flex flex-wrap align-center margin-top-sm">
                <div v-for="(item,index) in cuForm.pics" :key="index"
                     class="flex flex-direction align-center justify-between margin-left"
                >
                  <el-image style="width: 100px;height: 160px;" :src="item.pic_url" fit="contain"
                            :preview-src-list="picList"
                  />
                  <div>{{ item.uuid }}</div>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleFrameSupplier = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitFrameSupplier">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 自助选位(弹出框) -->
    <position-selection :dialog-show="dialogVisiblePositionSelection" :component-type="2"
                        @close="closePositionSelection" @save="savePositionSelection"
    />

    <!-- 新增点位(弹出框) -->
    <el-dialog title="新增点位" :visible.sync="dialogVisibleAddMedia" width="60%" center>
      <el-form ref="cuFormAddMedia" v-loading="dialogLoading" :model="cuFormAddMedia" size="mini">
        <div class="margin-bottom-sm text-right" style="margin-top: -5px;">
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addMediaRow">新增
          </el-button>
        </div>

        <el-table :data="tableDataAddMedia" size="mini" style="width: 100%;margin-bottom: 15px;">
          <el-table-column prop="media_type" label="媒体类型" min-width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-form-item prop="rulesComm" :rules="rulesComm('select', '媒体类型', row.media_type)">
                <el-select v-model="row.media_type" clearable value-key="id" placeholder="请选择媒体类型"
                           @change="changeMediaType($index, row)"
                >
                  <el-option v-for="item in mediaTypeArr" :key="item.id" :label="item.name" :value="item" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="media_type_spec" label="尺寸" min-width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-form-item prop="rulesComm" :rules="rulesComm('specs', '尺寸', row.media_type_spec)">
                <el-select v-model="row.media_type_spec" clearable filterable allow-create default-first-option
                           value-key="name" placeholder="请输入尺寸（宽*高）" @change="changeMediaTypeSpec($index, row)"
                >
                  <el-option v-for="item in mediaTypeSpecArr" :key="item.name" :label="item.name" :value="item" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="media_pic_type" label="材质" min-width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-form-item prop="rulesComm" :rules="rulesComm('select', '材质', row.media_pic_type)">
                <el-select v-model="row.media_pic_type" clearable value-key="name" placeholder="请选择材质">
                  <el-option v-for="item in mediaPicTypeArr" :key="item.id" :label="item.name" :value="item" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" min-width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-form-item prop="rulesComm" :rules="rulesComm('count', '数量', row.count)">
                <el-input v-model.trim="row.count" clearable type="number" placeholder="请输入数量" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="100" align="center">
            <template slot-scope="{row,$index}">
              <el-button type="text" size="mini" @click.native.prevent="delMediaRow($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        </table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAddMedia = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitAddMedia">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 标记(弹出框) -->
    <el-dialog title="标记" :visible.sync="dialogVisibleSign" width="35%" center>
      <el-form ref="signForm" v-loading="dialogLoading" :model="cuFormSign" class="" label-position="right"
               label-width="100px" :rules="signFromRules"
      >
        <el-form-item label="标记类型" prop="mark_info">
          <el-select v-model="cuFormSign.mark_info" clearable value-key="id" placeholder="请选择标记类型" style="width: 100%">
            <el-option v-for="(item,index) in dictMarkArr" :key="item.id" :value="item" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="mark_memo">
          <el-input v-model.trim="cuFormSign.mark_memo" type="textarea" rows="3" placeholder="请输入备注" clearable />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSign = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitSign">确 定</el-button>
      </span>
    </el-dialog>

    <el-image-viewer v-if="dialogVisibleViewer" :on-close="closeViewer"
                     :url-list="cuForm.type===1?picList:uploadPicList" :initial-index="viewerIndex" :z-index="3000"
    />

  </div>
</template>

<script>
import { get_company } from '@/api/system/department'
import { list_latest_for_ad_make_by_dept_id } from '@/api/contract'
import { list_latest_for_ad_make_by_customer_id } from '@/api/merketOrder'
import { list_media_types } from '@/api/building/building'
import { list_by_material_id } from '@/api/supplier/supplier'
import { list_all3rd_bycode } from '@/api/business/setting/dict'
import {
  list_media_type_spec,
  list_media_pic_type,
  points_from_market,
  get_deliver_type,
  list,
  save,
  begin
} from '@/api/business/ad_make_order'

import { cloneDeep } from 'lodash'
import FlowBtnRow from '@/components/FlowBtnRow/index'
import PositionSelection from '@/components/PointPlanSetting/positionSelection'
import UploadImage from '@/components/upload'
import common from '@/utils/common.js'
import { generateUUID, formatDateByFmt } from '@/utils/util'
import { mergeTableRow } from '@/utils/table'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { company_list_all } from '@/api/customer/customer'

export default {
  name: 'CreateAdMakeOrderDetail',
  components: {
    FlowBtnRow,
    PositionSelection,
    UploadImage,
    ElImageViewer
  },
  data() {
    /**
       * 校验公共类
       *
       * type: text(输入框) select(下拉框) count(数值输入框) textarea(文本框)
       * required: 是否校验
       * message: 校验失败显示内容
       * data: 数据
       * params: 参数object类型
       * callback: 回调函数
       */
    var validatorComm = (type, required, message, data, params, callback) => {
      if (data) {
        if (type === 'count') {
          if (!/^[0-9]+[0-9]*[0-9]*$/.test(data)) callback(new Error('请输入正整数'))
          if (params && +params < data) callback(new Error('允许输入的最大数量为' + params))
        }
        if (type === 'price') {
          if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(data)) callback(new Error('请输入合法数字(支持2位小数)'))
        }
        if (type === 'textarea') {
          if (params && params < data.length) callback(new Error('允许输入最多' + params + '个字符串'))
        }
        if (type === 'specs') {
          if (!/^(\b[1-9]\d{0,1}\b|\b[1-9]\d{1,4}\b|\b99999\b)([*])(\b[1-9]\d{0,1}\b|\b[1-9]\d{1,4}\b|\b99999\b)$/
            .test(
              data.name || data)) {
            callback(new Error('格式宽*高，范围1-99999'))
          }
        }
        callback()
      } else if (required) callback(new Error((type === 'select' ? '请选择' : '请输入') + message)) // 验证不通过
      callback() // 验证通过
    }

    return {
      cuForm: {
        type: 1,
        dept_id: null,
        contract_id: null,
        customer_id: null,
        bill_market_id: null,
        bill_market_detail_id: null,
        dict_class_out_id: null,
        dict_class_in_id: null,
        memo: null,
        marks: [],
        pics: [],
        diss: [],
        delivers: [],
        contract_info: null,
        market_info: null,
        daterange_start: null,
        daterange_end: null,
        dict_class_out_name: null,
        has_sample: false
      },
      rules: {
        dept_id: [
          { required: true, message: '请选择公司', trigger: 'change' }
        ],
        contract_id: [
          { required: true, message: '请选择合同', trigger: 'change' }
        ],
        contract_info: [
          { required: true, message: '请选择合同', trigger: 'change' }
        ],
        customer_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        bill_market_id: [
          { required: true, message: '请选择时间段', trigger: 'change' }
        ]
      },
      rulesCommNoRequired: (type, content, data) => {
        return [{
          validator: (rule, value, callback) => {
            validatorComm(type, false, content, data, 200, callback)
          },
          trigger: type === 'select' ? 'change' : 'blur'
        }]
      },
      rulesComm: (type, content, data) => {
        return [{
          validator: (rule, value, callback) => {
            validatorComm(type, true, content, data, 200, callback)
          },
          trigger: (type === 'select' || type === 'specs') ? 'change' : 'blur'
        }]
      },
      rulesCount: (maxCount, data) => {
        return [{
          validator: (rule, value, callback) => {
            validatorComm('count', false, '', data, +maxCount, callback)
          },
          trigger: 'blur'
        }]
      },
      params: {},
      companyArr: [],
      contractArr: [],
      marketArr: [],
      supplierObj: {},
      dictInTypeArr: [],
      dictMarkArr: [],
      dictRunArr: [],
      mediaTypeArr: [],
      mediaTypeSpecArr: [],
      mediaPicTypeArr: [],
      // 历史单
      tableDataHistory: [],
      // 点位详情相关数据
      picList: [], // 画面url数组，用于预览
      uploadPicVOList: [], // 上传画面显示url数组
      uploadPicList: [], // 上传画面url数组
      tableDataMedia: [],
      tableDataMedia_out: [], // 外单选位数据
      // 自助选位相关数据
      dialogVisiblePositionSelection: false,
      // 新增点位相关数据
      dialogVisibleAddMedia: false,
      cuFormAddMedia: {},
      tableDataAddMedia: [],
      // 综合市场画面选择相关数据
      multipleSelection: [],
      dialogVisibleFrameAll: false,
      cuFormFrameAll: { name: null },
      tableDataFrameAll: [],
      // 画面选择相关数据
      dialogVisibleFrame: false,
      cuFormFrame: {},
      tableDataFrame: [],
      // 分配供应商相关数据
      dialogVisibleFrameSupplier: false,
      cuFormFrameSupplier: {},
      tableDataFrameSupplier: [],
      tableDataSupplier: [],
      tableDataSampleDeliver: [],
      tableDataDeliver: [],
      deliverTypeSampleList: [], // 小样配送方式
      deliverTypeList: [], // 配送方式
      // 标记相关数据
      dialogVisibleSign: false,
      cuFormSign: {
        mark_info: null,
        mark_memo: null
      },
      signFromRules: {
        mark_info: [
          { required: true, message: '请选择标记类型', trigger: 'change' }
        ],
        mark_memo: [
          { required: true, message: '请输入备注', trigger: 'blur' },
          { max: 10, message: '最多只允许输入200个字符串', trigger: 'blur' }
        ]
      },

      formLoading: false,
      formatDate: formatDateByFmt(new Date(), 'yyyy年MM月dd日'),
      dialogLoading: false,
      totalFrameCount: {}, // 已选择的画面数量
      dialogVisibleViewer: false,
      viewerIndex: 0,
      customer_arr: []
    }
  },
  computed: {
    userId() {
      return this.$store.state.user.id
    }
  },
  watch: {
    tableDataMedia: {
      deep: true, // 深度监听
      async handler(newVal, oldVal) {
        const that = this
        setTimeout(function() {
          console.log('tableDataMedia', newVal, oldVal)
          var tableData = that.tableDataFrameSupplier
          var total_obj = {} // 画面名称 和 材质 作为key
          for (var i in newVal) {
            var obj = newVal[i]
            var len = obj.media_type_id === 9 ? 5 : 3
            var list = obj.list
            var total = 0
            var obj = {}
            var table = that.$el.querySelector('#tableDataMedia_' + i)
            if (!table) continue
            var current = table.querySelector('.el-table__footer-wrapper')
              .querySelector('.el-table__footer')
            var cell = current.rows[0].cells
            cell[0].innerHTML = '合计'
            cell[1].colSpan = len
            cell[1].style.textAlign = 'center'
            cell[2].style.display = 'none'
            cell[3].style.display = 'none'
            if (len > 3) {
              cell[4].style.display = 'none'
              cell[5].style.display = 'none'
            }
            // 合计显示处理
            for (var x in list) {
              var o = list[x]
              var media_pic_type_id = o.media_pic_type_id
              var choose_info = o.choose_info
              total += +o.count
              for (var y in choose_info) {
                var o2 = choose_info[y]
                var name = o2.name
                var count = +o2.count
                if (obj[name]) {
                  obj[name] += count
                } else {
                  obj[name] = count
                }
                // 存在分配供应商数据时
                if (total_obj[name + '_' + media_pic_type_id]) {
                  total_obj[name + '_' + media_pic_type_id] += count
                } else {
                  total_obj[name + '_' + media_pic_type_id] = count
                }
              }
            }
            var str = '<div style="font-size: 14px;font-weight: 600;">'
            str += '<span>总数（' + total + '）</span>'
            for (var z in obj) {
              str += '<span class="text-red" style="margin-left:15px;">' + z + '（' + obj[z] + '）</span>'
            }
            str += '<div>'
            cell[1].innerHTML = str
          }
          // 更新分配供应商数据的choose_info
          for (var i in tableData) {
            var o = tableData[i]
            var media_pic_type_id = o.media_pic_type_id
            var choose_info = o.choose_info
            for (var x in choose_info) {
              var o2 = choose_info[x]
              var name = o2.name
              if (total_obj[name + '_' + media_pic_type_id]) {
                choose_info[x].count = total_obj[name + '_' +
                    media_pic_type_id]
              }
            }
            that.$set(that.tableDataFrameSupplier[i], 'choose_info', choose_info)
          }
          that.totalFrameCount = total_obj
        }, 50)
      }
    }
  },
  created() {
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params

    // 初始化
    this.getCompanyList()
    this.getDictInTypeList()
    this.getDictMarkList()
    this.getDeliverTypeSampleList()
    this.getDeliverTypeList()
    this.getDictRunList()
    this.getMediaTypeList()
    this.getDictMediaPicTypeList()
    this.initCustomerArr()
  },
  methods: {
    // api请求
    getCompanyList() { // 获取公司列表
      get_company().then(res => {
        this.companyArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.head
          }
        })
      })
    },
    getContractListByDeptId(customer_id) { // 根据deptId获取合同列表(包含项目信息)
      list_latest_for_ad_make_by_dept_id({
        customer_id: customer_id
      }).then(res => {
        this.contractArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.part_a + '（' + item.contract_begin_date + '~' + item.contract_end_date + '）' + '——' +
                item.contract_num,
            customer_id: item.customer_id,
            customer_name: item.customerName
          }
        })
      })
    },
    getMarketList(customerId) { // 根据customerId获取市场单列表
      list_latest_for_ad_make_by_customer_id({
        customerId: customerId
      }).then(res => {
        console.log(res.data)
        this.marketArr = res.data.map(item => {
          return {
            id: item.id,
            bill_market_detail_id: item.bill_market_detail_id,
            name: item.daterange_start + '——' + item.daterange_end
          }
        })
      })
    },
    getMarketPointInfo(market_info, loading) { // 根据market_id获取市场单点位列表
      const that = this
      let market_id = market_info.id
      let market_detail_id = market_info.bill_market_detail_id
      // 根据bill_market_id 和 mark_status=1 获取历史制作单数据
      list({
        page: 1,
        page_size: 99,
        bill_market_id: market_id,
        bill_market_detail_id: market_detail_id,
        mark_status: 1
      }).then(res => {
        const {
          data
        } = res
        this.cuFormSign.mark_bill_ad_make_id = market_id
        this.tableDataHistory = data.records
      })
      points_from_market({
        market_id: market_id,
        market_detail_id: market_detail_id
      }).then(res => {
        const {
          data
        } = res
        const picList = data.picList
        const pointList = data.pointList
        if (!picList) {
          this.$message.error('没有画面')
          return fasle
        }
        if (picList.length > 26) {
          this.$message.error('暂时只支持26张画面份分配供应商')
          return fasle
        }
        this.cuForm.daterange_start = data.daterange_start
        this.cuForm.daterange_end = data.daterange_end
        this.cuForm.daterange_arr = [data.daterange_start, data.daterange_end]
        this.cuForm.dict_class_out_id = data.dict_class_out_id
        this.cuForm.dict_class_out_name = data.dict_class_out_name
        this.cuForm.has_sample = data.has_sample
        this.cuForm.pics = picList.map((item, index) => {
          return {
            uuid: that.setFrameName(index),
            pic_url: item
          }
        })
        const list = that.formatPoint(pointList)
        this.picList = picList
        this.tableDataMedia = cloneDeep(list)
        this.tableDataMedia_out = cloneDeep(list)

        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    getSupplierObj(materialId) { // 根据materialId获取供应商列表
      list_by_material_id({ materialId: materialId }).then(res => {
        this.$set(this.supplierObj, materialId, res.data.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        }))
      })
    },
    getDictInTypeList() { // 获取内单类型字典
      list_all3rd_bycode({ code: 'zzdxg-ndlx' }).then(res => {
        const {
          data
        } = res
        this.dictInTypeArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
        this.cuForm.dict_class_in_id = data && data.length && data[0].id
      })
    },
    getDictMarkList() { // 获取标记类型字典
      list_all3rd_bycode({ code: 'zzdxg-bjlx' }).then(res => {
        this.dictMarkArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
      })
    },
    getDeliverTypeSampleList() {
      get_deliver_type({ isSample: 1 }).then(res => {
        this.deliverTypeSampleList = res.data
      })
    },
    getDeliverTypeList() {
      get_deliver_type({ isSample: 0 }).then(res => {
        this.deliverTypeList = res.data
      })
    },
    getDictRunList() { // 获取跑腿平台类型
      list_all3rd_bycode({ code: 'zzdxg-ptpt' }).then(res => {
        this.dictRunArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })
      })
    },
    getMediaTypeList() { // 获取媒体类型
      list_media_types().then(res => {
        this.mediaTypeArr = res.data.filter(item => item.id !== 11)
      })
    },
    getMediaTypeSpecList(media_type_id) { // 根据媒体类型id获取规格
      list_media_type_spec({
        media_type_id: media_type_id
      }).then(res => {
        this.mediaTypeSpecArr = res.data
      })
    },
    getMediaPicTypeList(media_type_id, size_width, size_height) { // 根据媒体类型id、规格获取材质
      list_media_pic_type({
        media_type_id: media_type_id,
        size_width: size_width,
        size_height: size_height
      }).then(res => {
        this.mediaPicTypeArr = res.data
      })
    },
    getDictMediaPicTypeList() {
      list_all3rd_bycode({ code: 'dwxg-hmsx' }).then(res => {
        this.mediaPicTypeArr = res.data
      })
    },
    // 事件
    changeAdMakeType(e) { // 类型切换
      const that = this
      const uploadPicList = this.uploadPicList
      this.resetPointAndSupplier(false, () => {
        if (e === 2 && uploadPicList.length) {
          that.cuForm.pics = uploadPicList.map((item, index) => {
            return {
              uuid: that.setFrameName(index),
              pic_url: item
            }
          })
          that.uploadPicVOList = uploadPicList.map((item, index) => {
            return {
              url: item
            }
          })
          that.picList = cloneDeep(uploadPicList)
        }
      })
    },
    changeCompany(e) { // 公司切换(外单)
      if (e) {
        this.resetPointAndSupplier(true)
        // this.getContractListByDeptId(e)
      }
    },
    changeContract(e) { // 合同切换(外单)
      if (e) {
        this.resetPointAndSupplier()
        this.getMarketList(e.customer_id)
      }
    },
    changeMarket(e) { // 时间段切换(外单)
      if (e) {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.cuForm.bill_market_id = e.id
        this.cuForm.bill_market_detail_id = e.bill_market_detail_id
        this.getMarketPointInfo(e, loading)
      }
    },
    // 重置点位详情、分配供应商数据
    resetPointAndSupplier(has_contract, callback) {
      if (has_contract) this.cuForm.contract_info = null
      this.cuForm.bill_market_id = null
      this.cuForm.daterange_start = null
      this.cuForm.daterange_end = null
      this.cuForm.dict_class_out_id = null
      this.cuForm.dict_class_out_name = null
      this.cuForm.has_sample = null
      this.cuForm.pics = []
      this.picList = []
      this.tableDataHistory = []
      this.tableDataMedia = []
      this.tableDataMedia_out = []
      this.tableDataSupplier = []
      this.tableDataSampleDeliver = []
      this.tableDataDeliver = []
      this.$nextTick(function() {
        this.$refs['cuForm'].clearValidate()
        if (callback && typeof callback === 'function') callback()
      })
    },
    // 画面编号设置
    setFrameName(i) {
      const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      return str.substr(i, 1)
    },
    // 点位数据格式化
    formatPoint(list) {
      var list_1 = [] // 用于存放综合市场数据
      var list_2 = []
      var obj = {}
      for (var i in list) {
        var o = list[i]
        o.idx = i
        var media_type_id = o.media_type_id
        var media_type = o.media_type
        if (obj[media_type_id]) {
          obj[media_type_id].list.push(o)
        } else {
          obj[media_type_id] = {
            id: media_type_id,
            name: media_type,
            list: [o]
          }
        }
      }
      for (var i in obj) {
        var item = obj[i]
        if (i == 9) {
          list_1.push(item)
        } else {
          list_2.push(item)
        }
      }
      return list_1.concat(list_2)
    },
    toDetail(id) {
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          id: id
        }
      })
      this.$router.push({
        name: 'look_ad_make_order_detail',
        query: {
          uuid
        }
      })
    },
    // 上传图片相关事件
    handleUploadSuccess(e) {
      this.commUploadPic(e)
    },
    handleUploadRemove(e) {
      this.commUploadPic(e)
    },
    handleUploadPreview(e) {
      var viewerIndex = 0
      var url = e.id ? e.url : (e.response && e.response.e || e)
      var uploadPicList = this.uploadPicList
      for (var i in uploadPicList) {
        var o = uploadPicList[i]
        if (o == url) viewerIndex = +i
      }
      this.viewerIndex = viewerIndex
      this.dialogVisibleViewer = true
    },
    closeViewer() {
      this.dialogVisibleViewer = false
    },
    commUploadPic(data) {
      const that = this
      var pics = []
      var picList = []
      for (var i in data) {
        var o = data[i]
        var url = ''
        if (o.id) {
          url = o.url
        } else {
          url = o.response && o.response.data || o
        }
        pics.push({
          uuid: that.setFrameName(i),
          pic_url: url
        })
        picList.push(url)
      }
      this.cuForm.pics = pics
      this.picList = cloneDeep(picList)
      this.uploadPicList = cloneDeep(picList)
    },
    // 点位详情table相关事件
    selectionChange(e) { // 多选
      this.multipleSelection = e
    },
    getSummariesMedia(param) { // 合计
      const {
        columns,
        data
      } = param
      const that = this
      const sums = []
      return sums
    },
    // 自助选位(弹出框)相关事件
    showPositionSelection() {
      if (!this.picList.length) {
        this.$message.error('请先上传画面')
        return false
      }
      this.dialogVisiblePositionSelection = true
    },
    closePositionSelection() {
      this.dialogVisiblePositionSelection = false
    },
    savePositionSelection(e) {
      this.tableDataMedia = e
      this.dialogVisiblePositionSelection = false
    },
    // 新增点位(弹出框)相关事件
    showAddMedia() { // 显示新增点位塘出口
      if (this.cuForm.type === 2 && !this.picList.length) {
        this.$message.error('请先上传画面')
        return false
      }
      this.dialogVisibleAddMedia = true
      this.dialogLoading = true
      this.$nextTick(() => {
        this.$refs['cuFormAddMedia'].resetFields()
        if (this.tableDataAddMedia.length === 0) this.addMediaRow()
        this.dialogLoading = false
      })
    },
    addMediaRow() { // 新增点位行
      this.tableDataAddMedia.push({})
    },
    delMediaRow(index) { // 删除点位行
      this.tableDataAddMedia.splice(index, 1)
    },
    changeMediaType(index, row) { // 媒体类型选择事件
      const media_type_id = row.media_type.id
      this.mediaTypeSpecArr = []
      // this.mediaPicTypeArr = []
      this.$set(this.tableDataAddMedia[index], 'media_type_spec', null)
      this.$set(this.tableDataAddMedia[index], 'media_pic_type', null)
      if (media_type_id) this.getMediaTypeSpecList(media_type_id)
    },
    changeMediaTypeSpec(index, row) { // 规格选择类型
      // const media_type_id = row.media_type.id,
      //   media_type_spec = row.media_type_spec
      // this.mediaPicTypeArr = []
      // this.$set(this.tableDataAddMedia[index], 'media_pic_type', null)
      // this.getMediaPicTypeList(media_type_id, media_type_spec.size_width, media_type_spec.size_height)
      // 处理select创建条目的数据
      var media_type_spec = row.media_type_spec
      if (media_type_spec && typeof (media_type_spec) === 'string') {
        var arr = media_type_spec.split('*')
        this.$set(this.tableDataAddMedia[index], 'media_type_spec_out', {
          name: media_type_spec,
          size_width: arr[0],
          size_height: arr[1]
        })
      }
    },
    onSubmitAddMedia() { // 确定新增点位数据
      this.$refs['cuFormAddMedia'].validate((valid) => {
        if (valid) {
          const tableData = this.tableDataAddMedia
          const type = this.cuForm.type
          var obj = {}
          var list_9 = []
          var list = []
          // 处理新增点位数据，数据格式{id:'媒体类型id',name:'媒体类型name',list:{'宽_高_材质id':object}}
          for (var i in tableData) {
            var o = tableData[i]
            var media_type_obj = o.media_type
            var media_type_spec_obj = typeof (o.media_type_spec) === 'string' ? o.media_type_spec_out : o
              .media_type_spec
            var media_pic_type_obj = o.media_pic_type
            var id = media_type_obj.id
            var name = media_type_obj.name
            var size_width = media_type_spec_obj.size_width
            var size_height = media_type_spec_obj.size_height
            var media_pic_type_id = media_pic_type_obj.id
            var key = size_width + '_' + size_height + '_' + media_pic_type_id
            var item = {
              name: name,
              media_type_id: id,
              media_type: name,
              media_type_spec: media_type_spec_obj.name,
              size_width: size_width,
              size_height: size_height,
              media_pic_type_id: media_pic_type_id,
              media_pic_type: media_pic_type_obj.name,
              count: +o.count
            }
            if (obj[id]) {
              if (obj[id].list[key]) {
                obj[id].list[key].count += +o.count
              } else {
                obj[id].list[key] = item
              }
            } else {
              obj[id] = {
                id: id,
                name: name,
                list: {
                  [key]: item
                }
              }
            }
          }
          // 如果是外单新增点位，需要数据合并处理
          if (type === 1) {
            const tableDataMedia_out = this.tableDataMedia_out
            for (var x in tableDataMedia_out) {
              var o = tableDataMedia_out[x]
              var arr = o.list
              var item = {}
              for (var y in arr) {
                var o2 = arr[y]
                item[o2.size_width + '_' + o2.size_height + '_' + o2.media_pic_type_id] = Object.assign({
                  has_add: true
                }, o2)
              }

              if (obj[o.id]) { // 新增点位数据存在该媒体类型，有同规格进行数量相加，无同规格则添加进obj
                var items = obj[o.id].list
                for (var z in items) { // obj对象
                  var o3 = items[z]
                  if (item[z]) {
                    obj[o.id].list[z].count += item[z].count
                    item[z].has_add = false
                  }
                }
                for (var z in item) { // 新增点位对象
                  var o3 = item[z]
                  if (o3.has_add) obj[o.id].list[z] = o3
                }
              } else {
                obj[o.id] = {
                  id: o.id,
                  name: o.name,
                  list: item
                }
              }
            }
          }
          // 处理最终显示数据，综合市场类型的显示在最前面
          for (var x in obj) {
            var item = obj[x]
            var items = item.list
            var arr = []
            for (var y in items) {
              arr.push(items[y])
            }
            item.list = arr.sort((a, b) => { // 按尺寸排序
              return b.media_type_spec.localeCompare(a.media_type_spec)
            })
            if (x == 9) {
              list_9.push(item)
            } else {
              list.push(item)
            }
          }
          this.tableDataMedia = list_9.concat(list)
          this.dialogVisibleAddMedia = false
        }
      })
    },
    // 综合市场选择画面(弹出框)相关事件
    showChooseFrameAll() { // 显示综合市场选择画面弹出框
      this.dialogVisibleFrameAll = true
      this.dialogLoading = true
      this.$nextTick(() => {
        this.$refs['cuFormFrameAll'].resetFields()
        this.cuFormFrameAll.name = 'A'
        this.tableDataFrameAll = this.multipleSelection
        this.dialogLoading = false
      })
    },
    onSubmitFrameAll() { // 确定综合市场选择画面
      this.$refs['cuFormFrameAll'].validate((valid) => {
        if (valid) {
          const selectList = this.multipleSelection
          const list = this.tableDataMedia
          const name = this.cuFormFrameAll.name
          var ids = {}
          for (var i in selectList) {
            var obj = selectList[i]
            ids[obj.size_width + '_' + obj.size_height + '_' + obj.media_pic_type_id] = {
              idx: obj.idx,
              name: obj.name
            }
          }
          for (var i in list) {
            var obj = list[i]
            var arr = obj.list
            for (var y in arr) {
              var o = arr[y]
              var o2 = ids[o.size_width + '_' + o.size_height + '_' + o.media_pic_type_id]
              if (o2 && o2.idx === y) {
                this.$set(this.tableDataMedia[i].list[y], 'choose_info', [{ name: name, count: o.count }])
              }
            }
          }
          this.$refs['tableDataMedia_0'][0].clearSelection()
          this.dialogVisibleFrameAll = false
        }
      })
    },
    // 选择画面(弹出框)相关事件
    showChooseFrame(row, index, idx) {
      console.log('showChooseFrame', row, index, idx)
      this.dialogVisibleFrame = true
      this.dialogLoading = true
      this.$nextTick(() => {
        this.$refs['cuFormFrame'].resetFields()
        var obj = {
          index: index,
          idx: idx,
          media_type_id: row.media_type_id,
          media_pic_type: row.media_pic_type,
          max_count: row.count
        }
        var choose_info = row.choose_info
        var picList = this.cuForm.pics
        if (choose_info && choose_info.length) {
          for (var i in choose_info) {
            var o = choose_info[i]
            obj[o.name] = o.count
          }
        } else {
          for (var i in picList) {
            var o = picList[i]
            obj[o.name] = null
          }
        }
        this.cuFormFrame = obj
        this.tableDataFrame = [row]
        this.dialogLoading = false
      })
    },
    onSubmitFrame() {
      this.$refs['cuFormFrame'].validate((valid) => {
        if (valid) {
          var data = this.cuFormFrame
          var picList = this.cuForm.pics
          var count = 0
          var choose_info = []
          for (var i in picList) {
            var obj = picList[i]
            var name = obj.uuid
            var num = parseInt(data[name] || 0)
            if (num) {
              choose_info.push({
                name: name,
                count: num
              })
              count += num
            }
          }
          if (count <= 0) {
            this.$message.error('至少给一个画面分配数量')
            return false
          }
          if (count > parseInt(data.max_count)) {
            this.$message.error('已分配的数量之和不能大于总分配数量')
            return false
          }
          this.$set(this.tableDataMedia[data.idx].list[data.index], 'choose_info', choose_info)
          this.dialogVisibleFrame = false
        }
      })
    },
    // 分配供应商(弹出框)相关事件
    showSupplier() {
      if (this.cuForm.type === 2 && !this.cuForm.pics.length) {
        this.$message.error('请先上传画面')
        return false
      }
      // 根据画面(幅) 和 材质处理数据
      const tableData = this.tableDataMedia
      var list = []
      var obj = {}
      var material_obj = {} // 材质obj
      for (var x in tableData) {
        var arr = tableData[x].list
        for (var y in arr) {
          var o = arr[y]
          var choose_info = o.choose_info
          if (choose_info && choose_info.length) {
            var media_pic_type_id = o.media_pic_type_id
            for (var z in choose_info) {
              var item = choose_info[z]
              var name = item.name
              var count = item.count
              if (obj[name + '_' + media_pic_type_id]) {
                obj[name + '_' + media_pic_type_id].choose_info[0].count += count
              } else {
                obj[name + '_' + media_pic_type_id] = {
                  choose_info: [{
                    name: name,
                    count: count
                  }],
                  media_pic_type_id: media_pic_type_id,
                  media_pic_type: o.media_pic_type
                }
              }
            }
            material_obj[media_pic_type_id] = media_pic_type_id
          }
        }
      }
      for (var i in obj) {
        var o = obj[i]
        list.push(o)
      }
      // 请求供应商列表
      for (var i in material_obj) {
        this.getSupplierObj(i)
      }
      if (!list.length) {
        this.$message.error('至少给一个点位分配画面')
        return false
      }
      this.dialogVisibleFrameSupplier = true
      this.dialogLoading = true
      this.$nextTick(() => {
        this.$refs['cuFormFrameSupplier'].resetFields()
        this.tableDataFrameSupplier = list
        this.dialogLoading = false
      })
    },
    onSubmitFrameSupplier() {
      this.$refs['cuFormFrameSupplier'].validate((valid) => {
        if (valid) {
          const tableData = this.tableDataFrameSupplier
          var list = []
          var obj = {}
          var supplierList = []
          var supplierObj = {}
          for (var i in tableData) {
            var o = tableData[i]
            var supplier_info = o.supplier_info
            var supplier_id = supplier_info.id
            var supplier_name = supplier_info.name
            var media_pic_type_id = o.media_pic_type_id
            if (obj[supplier_id + '_' + media_pic_type_id]) {
              obj[supplier_id + '_' + media_pic_type_id].choose_info.push(o.choose_info[0])
            } else {
              obj[supplier_id + '_' + media_pic_type_id] = {
                supplier_id: supplier_id,
                supplier_name: supplier_name,
                media_pic_type_id: o.media_pic_type_id,
                media_pic_type: o.media_pic_type,
                choose_info: o.choose_info
              }
            }
          }
          for (var i in obj) {
            var o = obj[i]
            var supplier_id = o.supplier_id
            o.choose_info = o.choose_info.sort((a, b) => { // 按画面别名排序
              return a.name.localeCompare(b.name)
            })
            list.push(o)
            if (!supplierObj[supplier_id]) {
              supplierObj[supplier_id] = {
                supplier_id: supplier_id,
                supplier_name: o.supplier_name
              }
            }
          }
          for (var i in supplierObj) {
            supplierList.push(supplierObj[i])
          }
          this.tableDataSupplier = list
          // 外单才有小样配送、配送方式数据
          if (this.cuForm.type === 1) {
            if (this.cuForm.has_sample) {
              this.tableDataSampleDeliver = Object.keys(supplierObj).map(key => {
                var o = supplierObj[key]
                return Object.assign({ sample: 1 }, o)
              })
            }
          }
          this.tableDataDeliver = Object.keys(supplierObj).map(key => {
            var o = supplierObj[key]
            return Object.assign({ sample: 0 }, o)
          })
          this.dialogVisibleFrameSupplier = false
        }
      })
    },
    editSupplierRow(row, index) {

    },
    delSupplierRow(index) {
      const supplier_id = this.tableDataSupplier[index].supplier_id
      const index2 = this.tableDataSampleDeliver.findIndex((item) => {
        return supplier_id === item.supplier_id
      })
      const index3 = this.tableDataDeliver.findIndex((item) => {
        return supplier_id === item.supplier_id
      })
      this.tableDataSupplier.splice(index, 1)
      this.tableDataSampleDeliver.splice(index2, 1)
      this.tableDataDeliver.splice(index3, 1)
    },
    // 标记(弹出框)相关事件
    handelSignFail(row, idx) {
      this.dialogVisibleSign = true
      this.$nextTick(() => {
        this.$refs['signForm'].resetFields()
        this.cuFormSign.row_idx = idx
      })
    },
    handelSignClear(row, idx) {
      this.$set(this.tableDataHistory[idx], 'mark_id', null)
      this.$set(this.tableDataHistory[idx], 'mark_name', null)
      this.$set(this.tableDataHistory[idx], 'mark_memo', null)
      this.$message.success('标记清除')
    },
    onSubmitSign() {
      this.$refs['signForm'].validate((valid) => {
        if (valid) {
          const data = this.cuFormSign
          const idx = data.row_idx
          const mark_info = data.mark_info
          this.$set(this.tableDataHistory[idx], 'mark_id', mark_info.id)
          this.$set(this.tableDataHistory[idx], 'mark_name', mark_info.name)
          this.$set(this.tableDataHistory[idx], 'mark_memo', data.mark_memo)
          this.$message.success('标记成功')
          this.dialogVisibleSign = false
        }
      })
    },
    // 审批流组件相关方法
    checkData(content, callback) {
      this.$refs['cuForm'].validate((valid) => {
        if (valid) {
          const ad_make_type = this.cuForm.type
          if (ad_make_type === 2 && this.uploadPicList.length === 0) {
            this.$message.error('请上传画面')
            return false
          }

          const tableDataSupplier = this.tableDataSupplier
          if (!tableDataSupplier.length) {
            this.$message.error('请分配供应商')
            return false
          }

          const tableDataHistory = this.tableDataHistory
          const tableDataMedia = this.tableDataMedia
          const tableDataSampleDeliver = this.tableDataSampleDeliver
          const tableDataDeliver = this.tableDataDeliver
          const contract_info = this.cuForm.contract_info
          const totalFrameCount = this.totalFrameCount
          var marks = []
          var diss = []
          var delivers = []
          var frameObj = {} // 画面对应的供应商
          var frameCountObj = {} // 画面_材质对应的数量

          for (var x in tableDataSupplier) {
            var o = tableDataSupplier[x]
            var choose_info = o.choose_info
            var media_pic_type_id = o.media_pic_type_id
            for (var y in choose_info) {
              var item = choose_info[y]
              var name = item.name
              frameObj[name + '_' + o.media_pic_type_id] = o.supplier_id
              frameCountObj[name + '_' + media_pic_type_id] = item.count
            }
          }

          // 校验选择的画面和分配的画面是否一致
          var flag = false
          for (var i in totalFrameCount) {
            var o = totalFrameCount[i]
            if (frameCountObj[i]) {
              if (frameCountObj[i] !== o) {
                flag = true
                break
              }
            } else {
              flag = true
              break
            }
          }
          if (flag) {
            this.$message.error('已选择的画面与分配的画面不一致，请重新分配供应商')
            return false
          }

          // 标记制作单
          for (var i in tableDataHistory) {
            var o = tableDataHistory[i]
            var mark_id = o.mark_id
            if (mark_id) {
              marks.push({
                mark_bill_ad_make_id: o.id,
                mark_id: o.mark_id,
                mark_memo: o.mark_memo
              })
            }
          }
          // 分配供应商
          for (var x in tableDataMedia) {
            var arr = tableDataMedia[x].list
            for (var y in arr) {
              var o = arr[y]
              var choose_info = o.choose_info
              for (var z in choose_info) {
                var item = choose_info[z]
                var name = item.name
                var media_pic_type_id = o.media_pic_type_id
                diss.push({
                  pic_uuid: name,
                  pic_type_id: media_pic_type_id,
                  supplier_id: frameObj[name + '_' + media_pic_type_id],
                  size_width: o.size_width,
                  size_height: o.size_height,
                  num: item.count
                })
              }
            }
          }
          // 配送方式
          for (var i in tableDataDeliver) {
            var o = tableDataDeliver[i]
            o.sample = 0
            delivers.push(o)
          }
          // 小样配送
          for (var i in tableDataSampleDeliver) {
            var o = tableDataSampleDeliver[i]
            o.sample = 1
            delivers.push(o)
          }
          var formData = Object.assign({}, this.cuForm)
          formData.type = null
          formData.dict_class_out_id = null
          formData.dict_class_in_id = null
          formData.contract_id = contract_info && contract_info.id || null
          formData.customer_id = contract_info && contract_info.customer_id || null
          formData.has_sample = null
          if (ad_make_type === 1) { // 外单数据设置
            formData.type = 0
            formData.dict_class_out_id = this.cuForm.dict_class_out_id == 1 ? 0 : 1
            formData.has_sample = this.cuForm.has_sample ? 1 : 0
          } else if (ad_make_type === 2) { // 内单数据设置
            formData.type = 1
            formData.dict_class_in_id = this.cuForm.dict_class_in_id
          }
          formData.marks = marks
          formData.diss = diss
          formData.delivers = delivers
          console.log('formData', formData)
          common.confirmDialog(content).then((confirm) => {
            if (confirm) {
              if (callback && typeof callback === 'function') callback(formData)
            }
          })
        }
      })
    },
    save() {
      this.checkData('您确定要保存?', (formData) => {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        save(formData).then(res => {
          loading.close()
          this.$message.success('保存成功')
          this.closeThisPage()
        }).catch(() => {
          loading.close()
        })
      })
    },
    submit() {
      this.checkData('您确定要提交?', (formData) => {
        const loading = this.$loading({
          lock: true,
          text: '提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        begin(formData).then(res => {
          loading.close()
          this.$message.success('提交成功')
          this.closeThisPage()
        }).catch(() => {
          loading.close()
        })
      })
    },
    // 关闭此页面
    closeThisPage() {
      this.$store.dispatch('tagsView/closePage', this.$route.name)
    },
    // 客户列表
    initCustomerArr() {
      company_list_all().then(res => {
        this.customer_arr = res.data
      }).catch(() => {
        this.customer_arr = []
      })
    },
    customerChange(customer_id) {
      this.cuForm.contract_info = null
      this.cuForm.bill_market_id = null
      this.$nextTick(() => {
        this.$refs.cuForm.clearValidate()
      })
      if (customer_id) {
        this.getContractListByDeptId(customer_id)
      }
    }
  }
}
</script>

<style scoped>
  .title {
    margin-top: 20px;
    font-size: 25px;
    font-weight: bold;
    text-align: center;
  }

  .header {
    width: 80%;
    margin: 0 auto;
    position: relative;
  }

  .content {
    margin-top: 20px;
  }

  .fill_date {
    font-weight: bold;
    position: absolute;
    right: 0;
    top: 16px;
    line-height: 25px;
  }

  .mailTable {
    width: 80%;
    font-size: 14px;
    margin: 0 auto 10px auto;
    border-collapse: collapse;
  }

  .mailTable tr td {
    height: 60px;
    line-height: 35px;
    box-sizing: border-box;
    padding: 0 10px;
    border-bottom: 1px solid #E6EAEE;
    border-right: 1px solid #E6EAEE;
    text-align: center;
  }

  .firstTr td {
    border-top: 1px solid #E6EAEE;
  }

  .firstTd {
    border-left: 1px solid #E6EAEE;
  }

  .mailTable tr td.column {
    text-align: center;
  }

  .tip {
    color: red;
    width: 200px;
  }

  .table-herder {
    background-color: #F5F7FA;
    font-weight: bold;
  }

  .tip_td {
    padding: 0 20px !important;
    background-color: #F5F7FA;
    font-weight: bold;
    width: 200px;
  }

  /deep/ .content .el-form-item {
    margin-bottom: 0;
  }

  /deep/ .el-card .el-card__body {
    padding: 0;
  }

  /deep/ .el-input.is-disabled .el-input__inner {
    color: #7f838d;
  }

  /deep/ .choosed-data {
    background-color: #e9f9ff !important;
  }

  .own-form__pic {
    text-align: left;
    padding: 15px 5px;
  }

  /deep/ .own-form__pic .el-form-item__content {
    line-height: 20px !important;
  }

  /deep/ .own-table .el-form-item {
    margin: 18px 0 !important;
  }

  .own-form__pic .upload-demo {
    width: 100%;
    margin: 0;
  }
</style>
